﻿namespace Triad.Controls
{
    #region Usings
    using System;
    using System.Data;
    using System.Text;
    using System.Web;
    using System.Web.UI.WebControls;
    #endregion

    public partial class tfListView
    {
        private string RenderClientSideCode()
        {
            var shtml = new StringBuilder();
            var strTemp = "<center>No Data Found</center>";
            shtml.AppendFormat("<div id=\"{0}Hdr\"></div>", ClientID);
            shtml.Append("<div id='");
            shtml.Append(ClientID);
            shtml.Append("Container'>");
            shtml.Append("<div id='");
            shtml.Append(ClientID);
            shtml.Append("RDiv' class='lvCon' style='width: ");
            shtml.Append(GridWidth);
            shtml.Append(";height:");
            shtml.Append(GridHeight);
            shtml.Append(";'");
            shtml.Append(" onscroll='");
            shtml.Append(ClientID);
            shtml.Append(".onScrollDiv();'");
            shtml.Append(">");
            shtml.Append(strTemp);
            shtml.Append("</div>");
            shtml.Append("<div class=\"tfLoad\" style=\"display:none;\" id=\"");
            shtml.Append(ClientID);
            shtml.Append("loadingDiv\">");
            shtml.Append("</div>");
            shtml.AppendFormat("<div id=\"{0}Ftr\"></div>", ClientID);
            shtml.AppendFormat(@"<div id={0}BMk></div>{1}<div id='{0}uimg' style='LEFT: 0px; VISIBILITY: hidden; POSITION: absolute; TOP: 0px'>EDev</div>{1}", ClientID, c_NewLine);
            

            return shtml.ToString();
        }
        private static string ConvertToHtmlData(string data)
        {
            data = data.Replace("\n", " ").Replace(Environment.NewLine, "<br />").Replace("\"", "\\\"");
            if (String.IsNullOrEmpty(data)) { data = "\\\"\\\""; }
            return HttpUtility.HtmlEncode(data);
        }
        
        public static bool IsNumeric(object p_Expression)
        {
            double retNum;
            bool isNum = Double.TryParse(Convert.ToString(p_Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
            return isNum;
        }

        private static string ConvertToHtmlData(DataRow row, DataColumn column)
        {
            if (column.DataType == typeof(string))
                return ConvertToHtmlData(row[column].ToString());
            if (column.DataType == typeof(DateTime))
                if (row[column] != DBNull.Value)
                {
                    var date = (DateTime)row[column];
                    return "new Date(" + date.Year + "," + date.Month + "," + date.Day + ")";
                }
                else
                {
                    return "null";
                }


            if ((column.DataType == typeof(int)) || (column.DataType == typeof(short)) || (column.DataType == typeof(Single)) ||
                (column.DataType == typeof(Double)) || (column.DataType == typeof(Decimal)) || (column.DataType == typeof(Byte)) || 
                (column.DataType == typeof(long)))
                return row[column] != DBNull.Value ? row[column].ToString() : "0";

            if (column.DataType == typeof(bool))
                return row[column] != DBNull.Value ? ((bool)row[column] ? "1" : "0") : "0";
            return column.DataType.ToString();
        }
        private string GetRowJS(DataTable table, DataRow row, int ri)
        {
            var eventArgs = new lvRowDataBindEventArgs(row);
            OnRowDataBind(eventArgs);

            var shtml = new StringBuilder();
            shtml.Append(ClientID + ".Datas.Insert(new Array(");

            for (int nX = 0; nX < Columns.Count; nX++)
            {
                DataControlField dataGridField = Columns[nX];

                if (dataGridField is ImageField)
                {
                    var boundField = (ImageField)dataGridField;
                    DataColumn column = table.Columns[boundField.DataImageUrlField];
                    if (column.DataType == typeof(string))
                    {
                        //var fldForURL = ConvertToHtmlData(row, table.Columns[boundField.DataNavigateUrlFields[0]]);
                        //var sTemp = string.Format(boundField.DataNavigateUrlFormatString, fldForURL);
                        shtml.AppendFormat("\"<img alt='{0}' src='{1}'  />\",", boundField.AlternateText,
                                           ConvertToHtmlData(row, column));
                    }
                    else
                    {
                        shtml.Append(ConvertToHtmlData(row, column) + ",");
                    }
                }
                else if (dataGridField is HyperLinkField)
                {
                    var boundField = (HyperLinkField)dataGridField;
                    DataColumn column = table.Columns[boundField.DataTextField];
                    if (column.DataType == typeof(string))
                    {
                        string fldForURL = ConvertToHtmlData(row, table.Columns[boundField.DataNavigateUrlFields[0]]);
                        string sTemp = string.Format(boundField.DataNavigateUrlFormatString, fldForURL);
                        shtml.AppendFormat("\"<a href='{0}'>{1}</a>\",", sTemp, ConvertToHtmlData(row, column));
                    }
                    else
                    {
                        shtml.Append(ConvertToHtmlData(row, column) + ",");
                    }
                }
                else if (dataGridField is LVBoundField)
                {
                    if (dataGridField.HeaderText.Equals("_tfAT"))
                    {
                        shtml.AppendFormat("\"{0}{1}\",",
                                           IsSelected(row) ? 1 : 0,
                                           IsDisabled(row) ? 1 : 0);
                    }
                    else if (dataGridField.HeaderText.Equals("_tfRI"))
                    {
                        shtml.AppendFormat("\"{0}\",", ri);
                    }
                    else
                    {
                        var boundField = (LVBoundField)dataGridField;
                        DataColumn column = table.Columns[boundField.DataField];
                        if (column.DataType == typeof(string) || column.DataType == typeof(char))
                        {
                                
                                if(String.IsNullOrEmpty(row[column].ToString())){
                                    shtml.Append("'',");
                                }
                                else{
                                    shtml.Append("\"" + ConvertToHtmlData(row, column) + "\",");
                                }
                        }
                        else
                        {
                                shtml.Append(ConvertToHtmlData(row, column) + ",");
                        }
                    }
                }
            }

            shtml.Length = shtml.Length - 1; // = html.TrimEnd(',');
            shtml.Append("));" + Environment.NewLine);
            return shtml.ToString();
        }
        private string GetColumnJS(DataControlField dataGridField, string className, bool isLastColumn)
        {
            var shtml = new StringBuilder();
            DataColumn column = null;
            string strType = "";
            string colWidth="60px";

            if (dataGridField.HeaderText.Equals("_tfAT"))
            {
                shtml.AppendFormat(
                    "var gridColumn = {0}.Columns.InsertColumn(tfStringField,\"{1}\",\"{2}\", true,\"{3}\",\"25px\");",
                    ClientID, "_tfAT", "", className);
                shtml.AppendFormat("gridColumn.Visible = {0};gridColumn.ReadOnly = true;gridColumn.DefaultValue = '00';gridColumn.DataType = 'System.String';gridColumn.ColumnName = '_tfAT';",AllowUserSelection.ToString().ToLower());
                return shtml.ToString();
            }

            if (dataGridField.HeaderText.Equals("_tfRI"))
            {
                shtml.AppendFormat(
                    "var gridColumn = {0}.Columns.InsertColumn(tfStringField,\"{1}\",\"{2}\", true,\"{3}\",\"0px\");",
                    ClientID, "_tfRI", "", className);
                shtml.Append("gridColumn.Visible = false;gridColumn.ReadOnly = true;gridColumn.DataType = 'System.String';gridColumn.ColumnName = '_tfRI';");
                return shtml.ToString();
            }

            if (dataGridField is ImageField)
            {
                var hlField = (ImageField)dataGridField;
                colWidth = hlField.ItemStyle.Width.ToString();
                
                shtml.AppendFormat(
                    "var gridColumn = {0}.Columns.InsertColumn(tfStringField,\"{1}\",\"{2}\", true,\"{3}\",\"{4}\");",
                    ClientID, hlField.DataImageUrlField, hlField.HeaderText, className, colWidth );
                shtml.Append("gridColumn.ColumnName = '" +  hlField.DataImageUrlField + "';");
                if (HiddenColumns == null){HiddenColumns = "*";}
                if (HiddenColumns.Contains(dataGridField.ToString()))
                {
                    shtml.Append("gridColumn.Visible = false;");
                }
                else
                {
                    shtml.Append("gridColumn.Visible = " + hlField.Visible.ToString().ToLower() + ";");
                }
            }
            else if (dataGridField is HyperLinkField)
            {
                var hlField = (HyperLinkField)dataGridField;
                colWidth = hlField.ItemStyle.Width.ToString();
                strType = "tfStringField";
                if (hlField.GetType() == typeof(string)) strType = "tfStringField";
                else if (hlField.GetType() == typeof(DateTime)) strType = "tfDateField";
                else if (hlField.GetType() == typeof(int)) strType = "tfNumberField";
                else if (hlField.GetType() == typeof(short)) strType = "tfNumberField";
                else if (hlField.GetType() == typeof(long)) strType = "tfNumberField";
                else if (hlField.GetType() == typeof(bool)) strType = "tfBooleanField";

                shtml.AppendFormat("var gridColumn = {0}.Columns.InsertColumn({1},\"{2}\",\"{3}\", true,\"{4}\",\"{5}\");",
                                   ClientID, strType, hlField.DataTextField, hlField.HeaderText, className,colWidth);
                shtml.Append("gridColumn.ColumnName = '" +  hlField.DataTextField + "';");
                if (ReadOnly)
                    shtml.Append("gridColumn.ReadOnly = true;");
                if (HiddenColumns == null) {
                    HiddenColumns = "*"; }
                if (HiddenColumns.Contains(hlField.DataTextField))
                {
                    shtml.Append("gridColumn.Visible = false;");    
                }
                else
                {
                    shtml.Append("gridColumn.Visible = " + hlField.Visible.ToString().ToLower() + ";");    
                }

            }
            else if (dataGridField is LVBoundField)
            {
               // bool isRelationColumn = false;
                var boundField = (LVBoundField)dataGridField;
                //column = table.Columns[boundField.DataField];
                //foreach (DataRelation relation in table.ParentRelations)
                //{
                //    if (relation.ChildColumns[0].ColumnName == boundField.DataField)
                //    {
                //        shtml.Append("var optionsx = new Array();");
                //        for (int nX = 0; nX < relation.ParentTable.Rows.Count; nX++)
                //        {
                //            DataRow row = relation.ParentTable.Rows[nX];
                //            shtml.Append("optionsx[" + nX + "] = new Array();");
                //            shtml.Append("optionsx[" + nX + "][0] = \"" + ConvertToHtmlData(row[0].ToString()) + "\"");
                //            shtml.Append("optionsx[" + nX + "][1] = \"" + ConvertToHtmlData(row[1].ToString()) + "\"");
                //            shtml.Append(c_NewLine);
                //        }
                //        shtml.Append("tfSelectboxField.DataSource = optionsx;");
                //        shtml.Append(c_NewLine);
                //        shtml.Append("var gridColumn = " + ClientID + ".Columns.InsertColumn( tfSelectboxField,\"" +
                //                     column.ColumnName + "\", \"" + boundField.HeaderText +
                //                     "\", true,\"SmlTblTitle3\");");
                //        shtml.Append(c_NewLine);
                //        isRelationColumn = true;
                //        break;
                //    }
                //}

                //if (isRelationColumn)
                //{
                //}
                //else
                //{
                 strType = "tfStringField";
                if (boundField.GetType() == typeof(string)) strType = "tfStringField";
                else if (boundField.GetType() == typeof(DateTime)) strType = "tfDateField";
                else if (boundField.GetType() == typeof(int)) strType = "tfNumberField";
                else if (boundField.GetType() == typeof(short)) strType = "tfNumberField";
                else if (boundField.GetType() == typeof(long)) strType = "tfNumberField";
                else if (boundField.GetType() == typeof(bool)) strType = "tfBooleanField";

                colWidth = boundField.ItemStyle.Width.ToString();
                
                shtml.AppendFormat("var gridColumn = {0}.Columns.InsertColumn({1},\"{2}\",\"{3}\", true,\"{4}\",\"{5}\");",
                                   ClientID, strType, boundField.DataField, boundField.HeaderText, className, colWidth);
                shtml.Append("gridColumn.ColumnName = '" +  boundField.DataField + "';");
                shtml.Append("gridColumn.DataType = '" + boundField.DataType + "';");
                shtml.Append("gridColumn.allowHTML = " + boundField.AllowHTML.ToString().ToLower() + ";");


                string tCols = "," + readOnlyColumns + ",";
                if (tCols.Contains("," + boundField + ",") || ReadOnly)
                {
                    shtml.Append("gridColumn.ReadOnly = false;");
                }
                else
                { shtml.Append("gridColumn.ReadOnly = " + boundField.ReadOnly.ToString().ToLower() + ";");}
                
                tCols = "," + hiddenColumns + ",";
                if (tCols.Contains(","+boundField+","))
                {
                    shtml.Append("gridColumn.Visible = false;");
                }
                else
                {
                    shtml.Append("gridColumn.Visible = " + boundField.Visible.ToString().ToLower() + ";");
                }

            }

            if (column != null)
            {
                shtml.Append("gridColumn.AllowDBNull = " + column.AllowDBNull.ToString().ToLower() + ";");
                shtml.Append("gridColumn.AutoIncrement = " + column.AutoIncrement.ToString().ToLower() + ";");
                shtml.Append("gridColumn.AutoIncrementStep = " + column.AutoIncrementStep + ";");
                shtml.Append("gridColumn.Unique = " + column.Unique.ToString().ToLower() + ";");
            }

            
            shtml.Append("gridColumn.DefaultValue = '';"); return shtml.ToString();
        }

        private string GetTemplateHTML(DataControlField dataGridField)
        {
            var shtml = new StringBuilder();
            //tfDataTable column;

            string strType = "";

            if (dataGridField.HeaderText.Equals("_tfAT") || dataGridField.HeaderText.Equals("_tfRI"))
            {
                return "";
            }

            if (dataGridField is ImageField)
            {
                var hlField = (ImageField)dataGridField;
                strType = hlField.ReadOnly ? "disabled" : "";
                shtml.AppendFormat(
                    "<tr><td>{0}</td><td><input id=\"#{1}\" name=\"#{1}\" type=\"text\" {2} /></td></tr>",
                    hlField.HeaderText, hlField.DataImageUrlField, strType);
            }
            else if (dataGridField is HyperLinkField)
            {
                var hlField = (HyperLinkField)dataGridField;
                shtml.AppendFormat(
                    "<tr><td>{0}</td><td><input id=\"#{1}\" name=\"#{1}\" type=\"text\" {2} /></td></tr>",
                    hlField.HeaderText, hlField.DataNavigateUrlFields, strType);
            }
            else if (dataGridField is BoundField)
            {
               // bool isRelationColumn = false;
                var boundField = (LVBoundField)dataGridField; // NORMAL FIELD 
                     strType = "tfStringField";
                    //if (column.DataType == typeof(string)) strType = "tfStringField";
                    //else if (column.DataType == typeof(DateTime)) strType = "tfDateField";
                    //else if (column.DataType == typeof(int)) strType = "tfNumberField";
                    //else if (column.DataType == typeof(short)) strType = "tfNumberField";
                    //else if (column.DataType == typeof(long)) strType = "tfNumberField";
                    //else if (column.DataType == typeof(bool)) strType = "tfBooleanField";

                    string strEnabled = boundField.ReadOnly ? "disabled" : "";
                    shtml.AppendFormat(
                        "<tr><td>{0}</td><td><input id=\"#{1}\" name=\"#{1}\" type=\"text\" {2} {3} /></td></tr>",
                        boundField.HeaderText, boundField.DataField, strType, strEnabled);
//                
            }
            return shtml.ToString();
        }

        /// <summary>
        /// Gets the template HTML based on a DataColumn.
        /// </summary>
        /// <param name="dataGridField">The data grid field.</param>
        /// <returns></returns>
        private string GetTemplateHTML(DataColumn dataGridField)
        {
            var shtml = new StringBuilder();
            string strType = "tfStringField";

            if (dataGridField.ColumnName.Equals("_tfAT") || dataGridField.ColumnName.Equals("_tfRI"))
            {
                return "";
            }
            string sType = "";
            string tCols = "," + ReadOnlyColumns + ",";
            if (tCols.Contains("," + dataGridField.ColumnName + ","))
            {
                sType = "disabled='disabled'";
            }
            switch(dataGridField.DataType.FullName)
            {
               case "System.String":
                    strType = "text";// "tfStringField";
                    break;
               case "System.DateTime":
                    strType = "text";// "tfDateField";
                    break;
               case "System.Decimal":
               case "System.Double":
               case "System.Int16":
               case "System.Int32":
               case "System.Int64":
               case "System.Int":
                    strType = "text";// "tfNumberField";
                    break;
               case "System.Boolean":
                    strType = "checkbox"; //"tfBooleanField";
                    break;
               case "System.Byte":
                    strType = "text";// "tfNumberField";
                    break;
               case "System.Char":
                    strType = "text";// "tfNumberField";
                    break;
            }

                shtml.AppendFormat("<tr><td>{0}</td><td><input id=\"#{1}\" name=\"#{1}\" type=\"{2}\" {3} /></td></tr>",
                    dataGridField.ColumnName, dataGridField.ColumnName, strType, sType);

            return shtml.ToString();
        }

    } //End class
} // End Namespace
